package ltd.dujiabao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ltd.dujiabao.eduservice.client.VodClient;
import ltd.dujiabao.eduservice.entity.EduChapter;
import ltd.dujiabao.eduservice.entity.EduVideo;
import ltd.dujiabao.eduservice.mapper.EduVideoMapper;
import ltd.dujiabao.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author dujiabao
 * @since 2021-04-21
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
  @Autowired
  VodClient vodClient;

  @Override
  public boolean removeByCourseId(String courseId) {
    // 查询所有视频来源，并删除
    QueryWrapper<EduVideo> wrapper = new QueryWrapper<EduVideo>().eq("course_id", courseId).select("video_source_id");
    List<EduVideo> videoList = list(wrapper);
    String ids = getVideoSourceIds(videoList); // 取出所有id，拼成字符串
    if (!StringUtils.isEmpty(ids))
      vodClient.removeVideo(ids);

    // 删除video的数据
    wrapper = new QueryWrapper<EduVideo>().eq("course_id", courseId);
    return remove(wrapper);
  }

  /**
   * 将EduVideo组成的list中的所有
   *
   * @param videoList
   * @return
   */
  private String getVideoSourceIds(List<EduVideo> videoList) {
    if (videoList == null) return null;  // 如果为null，直接返回
    videoList.removeIf(Objects::isNull);  // 删除所有为空的内容
    videoList.removeIf(item -> StringUtils.isEmpty(item.getVideoSourceId())); // 删除所有videoSourceId 为空的内容
    if (videoList.size() == 0) return null;  // 如果过滤只会为空，直接返回

    // 最后处理，将所有id拿出来拼
    StringBuilder result = new StringBuilder();
    for (EduVideo video : videoList) {
      String videoSourceId = video.getVideoSourceId();
      result.append(videoSourceId).append(",");
    }
    return result.substring(1, result.length() - 1); // 返回结果，去除最后一个","
  }


  @Override
  public boolean removeVideo(String id) {
    EduVideo video = getById(id);
    String videoId = video.getVideoSourceId();
    if (!StringUtils.isEmpty(videoId)) {
      vodClient.removeVideo(videoId);
    }
    return removeById(id);
  }


}
